package controller

import (
	"github.com/gin-gonic/gin"
	"go-web-app-demo/common"
	"go-web-app-demo/model"
	"go-web-app-demo/router"
	"go-web-app-demo/service"
	"go.uber.org/zap"
	"math/rand"
	"net/http"
	"strconv"
)

func init() {
	router.AddHandler(&router.Handler{
		Method:       "post",
		RelativePath: "/post",
		HandleFunc:   NewPost,
		NeedAuth:     false,
	})

	router.AddHandler(&router.Handler{
		Method:       "get",
		RelativePath: "/post/:id",
		HandleFunc:   GetPost,
		NeedAuth:     false,
	})

	router.AddHandler(&router.Handler{
		Method:       "get",
		RelativePath: "/post/list",
		HandleFunc:   ListPost,
		NeedAuth:     false,
	})
}

func NewPost(c *gin.Context) {

	req := new(model.CreatePostRequest)
	// demo 代码随便写一个id
	req.AuthorID = rand.Uint64()
	if err := c.ShouldBindJSON(req); err != nil {
		zap.L().Warn("请求参数错误", zap.Error(err))
		c.JSON(http.StatusBadRequest, common.NewFailed("参数错误"))
		return
	}

	c.JSON(http.StatusOK, service.NewPost(req))
}

func GetPost(c *gin.Context) {

	id, err := strconv.ParseUint(c.Param("id"), 10, 64)

	if err != nil {
		c.JSON(http.StatusBadRequest, common.NewFailed("参数错误"))
		return
	}

	c.JSON(http.StatusOK, service.GetPost(id))
}

// GetPostListHandler2 升级版帖子列表接口
// @Summary 升级版帖子列表接口
// @Description 可按社区按时间或分数排序查询帖子列表接口
// @Tags 帖子相关接口
// @Accept application/json
// @Produce application/json
// @Param Authorization header string false "Bearer 用户令牌"
// @Param object query models.ParamPostList false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} _ResponsePostList
// @Router /posts2 [get]
func ListPost(c *gin.Context) {

	var (
		page uint64
		size uint64
		err  error
	)

	if page, err = strconv.ParseUint(c.Query("page"), 10, 64); err != nil {
		page = 0
	}

	if size, err = strconv.ParseUint(c.Query("size"), 10, 64); err != nil {
		size = 10
	}

	if page > 0 {
		page -= 1
	}

	offset := page * size

	orderby := c.Query("orderby")
	cid, err := strconv.ParseUint(c.Query("cid"), 10, 64)

	if err != nil {
		c.JSON(http.StatusOK, common.NewFailed(err.Error()))
		return
	}
	rst := service.ListPostPage(offset, size, cid, orderby)

	c.JSON(http.StatusOK, &rst)
}
